package com.wlf.server.common.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.wlf.server.common.em.CacheKey;
import com.wlf.server.common.entity.RoleMenu;
import com.wlf.server.common.entity.RoleUser;
import com.wlf.server.common.entity.SysRole;
import com.wlf.server.common.mapper.SysRoleMapper;
import com.wlf.server.web.dto.MappingDTO;
import com.wlf.server.web.dto.RoleDTO;
import com.wlf.server.web.util.AjaxBean;
import com.wlf.server.web.util.JSON;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@CacheConfig(cacheNames = CacheKey.role)
public class SysRoleService extends ServiceImpl<SysRoleMapper, SysRole> {
    @Resource
    MappingDTO mappingDTO;
    /**
     * 获取单个角色对象,这是有缓存的
     */
    @Cacheable(key = "#id")
    public AjaxBean get(String id){
        return AjaxBean.getOkData(this.getById(id));
    }

    /**
     * 更新或者保存，更新时删除缓存
     */
    @CacheEvict(key = "#roleDTO.id",condition = "#roleDTO.id != null ")
    public AjaxBean saveOrUpdate(RoleDTO roleDTO){
        return AjaxBean.getByBool(Db.saveOrUpdate(mappingDTO.to(roleDTO)));
    }

    /**
     * 变更用户的角色信息
     * 清除用户缓存
     */
    @CacheEvict(cacheNames = CacheKey.user,allEntries = true)
    public AjaxBean changeRoleUser(String id,String userIds){
        // 先删除改角色ID下的所有用户
        Db.lambdaUpdate(RoleUser.class).eq(RoleUser::getRoleId,id).remove();
        ArrayList<RoleUser> roleUsers = new ArrayList<>();
        for (String s : JSON.parseArray(userIds,String.class)) {
            RoleUser roleUser = new RoleUser();
            roleUser.setRoleId(id);
            roleUser.setUserId(s);
            roleUsers.add(roleUser);
        }
        // 保存此角色拥有的用户信息
        Db.saveBatch(roleUsers);
        return AjaxBean.getOkMsg("更新成功");
    }

    /**
     * 保存角色对应的菜单信息
     */
    @CacheEvict(cacheNames = CacheKey.user,allEntries = true)
    public AjaxBean savaRoleMenu(String id, String menuIds){
        if (StrUtil.hasBlank(id)) return AjaxBean.getError("数据有误,角色更新失败");
        // 先删除全部
        Db.lambdaUpdate(RoleMenu.class).eq(RoleMenu::getRoleId, id).remove();
        List<String> menuIdList = JSON.parseArray(menuIds, String.class);
        ArrayList<RoleMenu> roleMenus = new ArrayList<>();
        for (String s : menuIdList) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(s);
            roleMenus.add(roleMenu);
        }
        Db.saveBatch(roleMenus);
        return AjaxBean.getOkMsg();
    }
}
